package com.sduept.nwld.dataserver.controller.mobiledata;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.primefaces.PrimeFaces;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.ReorderEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.web.core.manager.BannerManager;
import com.sduept.bigdata.web.core.model.BannerInfo;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.generator.ObjectId;
import com.sduept.utils.DateUtil;

@Named
@ViewScoped
public class BannerController extends AbstractController{
	/**
	 * 
	 */
	private static final long serialVersionUID = 3078991492234083432L;
	@Autowired
	private BannerManager bm;
	@Autowired
	private CommonDocumentProperties pros;
	private List<BannerInfo> banners = new ArrayList<BannerInfo>();
	private BannerInfo selected;
	private BannerInfo created;
	private UploadedFile newImageFile;
	private StreamedContent newImage;//新图片
	@SuppressWarnings("unused")
	private long milSeconds;
	
	private int interval = 30;
	private Date selectedOriginValidDate;
	//查询
	private Date sCreateTime;
	private Date eCreateTime;
	private String title;
	
	@PostConstruct
	public void init() {
		banners = bm.getBanners();
	}
	/*
	 * 查询
	 * */
	public void searchByCondition() {
		selected=null;
		banners=bm.getBannersByCondition(sCreateTime, eCreateTime, title);
	}
	/*
	 * 查询全部
	 * */
	public void searchAll() {
		sCreateTime=null;
		eCreateTime=null;
		title="";
		searchByCondition();
	}
	
	/**
	 * 选中左边轮播图列表
	 */
	public void onBannerSelect(SelectEvent event) {
		selected=(BannerInfo)event.getObject();
    }
	
	public void genCreateValidDate() {
		if(created != null) {
			DateTime dt = new DateTime();
			DateTime dt2 = dt.plusDays(interval);
			created.setValidDate(dt2.toDate());
		}
	}
	public void genSelectedValidDate() {
		if(selected != null) {
			DateTime dt=new DateTime(selected.getCreateDate().getTime());
			if(interval==0) {
				//选择自定义
				selected.setValidDate(selectedOriginValidDate);
			}else {
				DateTime dt2 = dt.plusDays(interval);
				selected.setValidDate(dt2.toDate());
			}
		}
	}
	//将轮播图列表中失效的和有效的记录用颜色分开
	public String getRowClass(BannerInfo banner) {
		Date validDate=banner.getValidDate();
		if(validDate.after(new Date())) {
			//有效
			return "effective";
		}
		return "inEffective";
	}
	
	/**
	 * 移动列表，改变顺序
	 */
	public void onRowReorder(ReorderEvent event) {
		int index=1;
	    for(BannerInfo d:banners){
	    	d.setOrderNo(index);
	    	index++;
	    	bm.createOrUpdate(d);
	    }
	}
	/**
	 * 编辑器保存内容
	 * */
	public void saveText(){
		String text=selected.getLink();
		/*if(StringUtils.isEmpty(selected.getTitle())) {
			addErrorMessage("标题不能为空！");
			return;
		}*/
		if(StringUtils.isNotEmpty(text)){
			try {
				bm.createOrUpdate(selected);
				addSuccessMessage("保存成功");
			} catch (Exception e) {
				e.printStackTrace();
				addErrorMessage("保存失败");
			}
		}else{
			addErrorMessage("内容为空！");
		}
	}
	/**
	 * 上传图片
	 * 
	 * @param event
	 */
    public void handleIconUpload(FileUploadEvent event){
    	newImageFile=event.getFile();
    	downloadNewImg();
    }
    //下载图片
  	private void downloadNewImg(){
  		if(newImageFile!=null){
  			try {
  				setNewImage(new DefaultStreamedContent(newImageFile.getInputstream(),
  						newImageFile.getContentType()));
  			} catch (IOException e) {
  				e.printStackTrace();
  			}
  		}
  	}
  	public void preCreate() {
  		interval = 30;
  		created=new BannerInfo();
  		DateTime dt = new DateTime();
		DateTime dt2 = dt.plusDays(interval);
  		created.setValidDate(dt2.toDate());
  		created.setCreator(getCurrentUser().getCode());
  		created.setCreateDate(dt.toDate());
  		created.setId(ObjectId.get().toString());
  	}
  	/**
  	 * 新建保存
  	 */
  	public void saveCreate() {
  		if(null!=newImageFile){
  			if(created.getValidDate()==null) {
  	  			addErrorMessage("有效期不能为空");
  	  			return;
  	  		}
  			uploadImg(created);
  			searchAll();
  			created.setOrderNo(banners.size()+1);
  			bm.createOrUpdate(created);
  			banners.add(created);
  			addSuccessMessage("保存成功");
  			PrimeFaces.current().executeScript("PF('createDlg').hide();");
  		}else{
  			addErrorMessage("请上传图片");
  		}
  	}
  	
  	public void preEdit() {
  		Date createD=selected.getCreateDate();
  		selectedOriginValidDate=selected.getValidDate();
  		interval = DateUtil.daysBetween(createD, selectedOriginValidDate);
  		if(interval!=7&&interval!=30&&interval!=90) {
  			interval=0;
  		}
  	}
  	/**
  	 * 编辑保存
  	 */
  	public void saveEdit() { 	
  		if(null!=newImageFile){
  			uploadImg(selected);
  		}
  		bm.createOrUpdate(selected);
  		addSuccessMessage("保存成功");
  	}
  	
  	private void uploadImg(BannerInfo target){
  		String oldIconName=target.getPath();
  		target.setName(newImageFile.getFileName());
		String houzhuiming = newImageFile.getFileName().substring(
				newImageFile.getFileName().lastIndexOf("."));
		String filePathName = ObjectId.get().toString() + houzhuiming;
		target.setPath(filePathName);
		String uploadpath = pros.getImagePath() + filePathName;
		try {
			FileOutputStream fos = new FileOutputStream(uploadpath);
			fos.write(newImageFile.getContents());
			fos.close();
			newImageFile = null;
			//删除原来的图片
			deleteImg(oldIconName);
		} catch (IOException ee) {
			addErrorMessage("上传失败");
		}
	}
  	private void deleteImg(String oldIconName){
		if(StringUtils.isNotEmpty(oldIconName)){
			File file=new File(pros.getImagePath() +oldIconName);
			if(file.exists()){
				file.delete();
			}
		}
	}
  	/**
  	 * 删除轮播图记录
  	 */
  	public void delete() {
  		//根据删除的位置，更新其他order
  		int index=selected.getOrderNo();
		bm.delete(selected);
		banners.remove(selected);
		for(int i=index-1;i<banners.size();i++){
	    	BannerInfo b=banners.get(i);
	    	b.setOrderNo(i+1);
	    	bm.createOrUpdate(b);
	    }
		selected = null;
		addSuccessMessage("删除成功");
	}
	public List<BannerInfo> getBanners() {
		return banners;
	}

	public void setBanners(List<BannerInfo> banners) {
		this.banners = banners;
	}

	public long getMilSeconds() {
		return System.currentTimeMillis();
	}
	public BannerInfo getSelected() {
		return selected;
	}
	public void setSelected(BannerInfo selected) {
		this.selected = selected;
	}

	public StreamedContent getNewImage() {
		return newImage;
	}

	public void setNewImage(StreamedContent newImage) {
		this.newImage = newImage;
	}

	public BannerInfo getCreated() {
		return created;
	}

	public void setCreated(BannerInfo created) {
		this.created = created;
	}

	public int getInterval() {
		return interval;
	}

	public void setInterval(int interval) {
		this.interval = interval;
	}

	public Date getsCreateTime() {
		return sCreateTime;
	}

	public void setsCreateTime(Date sCreateTime) {
		this.sCreateTime = sCreateTime;
	}

	public Date geteCreateTime() {
		return eCreateTime;
	}

	public void seteCreateTime(Date eCreateTime) {
		this.eCreateTime = eCreateTime;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

}
